<?php

namespace app\model\v1\gift;


use crmeb\traits\ModelTrait;
use think\Exception;
use think\facade\Db;
use think\Model;


class GiftCardBatch extends Model
{

    use ModelTrait;

    protected $updateTime = false;
    protected $createTime = false;

    protected $hidden = [
    //    'create_time','update_time','delete_time'
    ];

    protected $table = 'eb_gift_card_batch';



    /**
     * 实体卡批次管理列表
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getCardBatchList($params = [])
    {
        $data["data"] = self::field("*,FROM_UNIXTIME(create_time) as create_time")
            ->whereNull("delete_time")
            ->where(function ($query) use ($params){
                if(!empty($params['time'])){
                    $wheretime = explode (',',$params['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($params["word"])) $query->where("title",'like', '%'.$params["word"].'%');
            })
            ->order(['id'=>'desc'])
            ->page($params["page"], $params['limit'])
            ->select()->toArray();

        $data["count"] = self::field("*")
            ->whereNull("delete_time")
            ->where(function ($query) use ($params){
                if(!empty($params['time'])){
                    $wheretime = explode (',',$params['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($params["word"])) $query->where("title",'like', '%'.$params["word"].'%');
            })
            ->count();

        return $data;
    }


    /**
     * 实体卡批次管理列表 - 添加
     * @param $param
     * @return int|string
     */
    public static function addCardBatch($param = [])
    {
        try {
            Db::startTrans();

            $add = [
                "title"             => $param["title"] ?? '',
                "total_num"         => $param["total_num"] ?? '',
                "use_start_time"    => $param["use_start_time"] ?? '',
                "use_end_time"      => $param["use_end_time"] ?? '',
                "use_day"           => $param["use_day"] ?? '',
                "use_num"           => $param["use_num"] ?? '',
                "status"            => $param["status"] ?? '',
                "sort"              => $param["sort"] ?? '',
                "qrcode"            => $param["qrcode"] ?? '',
                "remark"            => $param["remark"] ?? '',
                "create_time"       => time(),
            ];
            $batch_id = self::insertGetId($add);

            $add_number = [];
            for($i=1; $i<=$param["total_num"]; $i++){
                $number = GiftCard::generateEntityNumber();
                $card_pwd = mt_rand(100000, 999999);

                $res = GiftCardNumber::createOne($batch_id, $number, $card_pwd, 0, $param["status"]);

                /*$add_number[] = [
                    "card_batch_id" => $batch_id,
                    "card_number"   => $number,
                    "card_password" => $card_pwd,
                    "status"        => $param["status"],
                    "use_time"      => time(),
                    "create_time"   => time(),
                ];*/
            }

            ////GiftCardNumber::createAll($add_number);


            Db::commit();

            return $batch_id;
        }catch (\Throwable $e){
            Db::rollback();
            Throw new Exception($e->getMessage());
        }
    }




    /**
     * 实体卡批次管理列表 - 编辑
     * @param $param
     * @return RecruitLanguage
     */
    public static function updateCardBatch($param = [])
    {
        $update["update_time"] = time();  //更新时间
        if(!empty($param["title"]))                $update["title"] = $param["title"];
        if(!empty($param["total_num"]))            $update["total_num"] = $param["total_num"];
        if(!empty($param["use_start_time"]))       $update["use_start_time"] = $param["use_start_time"];
        if(!empty($param["use_end_time"]))         $update["use_end_time"] = $param["use_end_time"];
        if(!empty($param["use_day"]))              $update["use_day"] = $param["use_day"];
        if(!empty($param["use_num"]))              $update["use_num"] = $param["use_num"];
        if(!empty($param["status"]))               $update["status"] = $param["status"];
        if(!empty($param["sort"]))                 $update["sort"] = $param["sort"];
        if(!empty($param["qrcode"]))               $update["qrcode"] = $param["qrcode"];
        if(!empty($param["remark"]))               $update["remark"] = $param["remark"];

        return self::where("id", $param["id"])->update($update);
    }



    /**
     * 实体卡批次管理列表 - 启用禁用
     * @param $param
     * @return string
     */
    public static function enableCardBatch($param = [])
    {
        //获取用户发送的id，根据状态修改当前banner的启用禁用状态
        $status = self::where("id", $param['id'])->value("status");
        $msg = '';
        if($status == 1){   //1启用 2禁用
            $enable = 2;
            $msg = "禁用成功";
        }else{
            $enable = 1;
            $msg = "启用成功";
        }
        self::where("id", $param['id'])->update(['status' => $enable]);
        return $msg;
    }


    /**
     * 获取礼品卡批次id
     * @param $param
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getCardBatchId()
    {
        $data = self::whereNull("delete_time")->where("status", 1)->order("id", "asc")->select()->toArray();
        $batch_id = '';
        foreach ($data as $key => $val){
            if($val["use_num"] < $val["total_num"]){
                $batch_id = $val["id"];
                break;
            }
        }
        return $batch_id;
    }




}